package com.ht.common.core.utils;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class EastPortHttpClientUtils {
  private static final Logger logger = LoggerFactory.getLogger(EastPortHttpClientUtils.class);
  
  private static HttpClient wrapClient() {
	    try {
	      SSLContext ctx = SSLContext.getInstance("TLS");
	      X509TrustManager tm = new X509TrustManager() {
	          @Override
			  public X509Certificate[] getAcceptedIssuers() {
	            return null;
	          }
			  @Override
	          public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
			  @Override
	          public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
	        };
	      ctx.init(null, new TrustManager[] { tm }, null);
	      SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, (HostnameVerifier) NoopHostnameVerifier.INSTANCE);
	      CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory((LayeredConnectionSocketFactory)ssf).build();
	      return (HttpClient)httpclient;
	    }catch (Exception e) {
	        return (HttpClient)HttpClients.createDefault();
	    } 
	  }
	
	public static String doPostApi(String url, String params) {
	    CloseableHttpClient httpclient = (CloseableHttpClient)wrapClient();
	    HttpPost httpPost = new HttpPost(url);
	    httpPost.setHeader("Accept", "application/json");
	    httpPost.setHeader("Content-Type", "application/json");
	    String charSet = "UTF-8";
	    logger.info("参数:{}",params);
	    StringEntity entity = new StringEntity(params, charSet);
	    httpPost.setEntity((HttpEntity)entity);
	    CloseableHttpResponse response = null;
	    try {
	      response = httpclient.execute((HttpUriRequest)httpPost);
	      logger.info("响应:{}",response);
	      StatusLine status = response.getStatusLine();
	      int state = status.getStatusCode();
	      if (state == 200) {
	        HttpEntity responseEntity = response.getEntity();
	        String jsonString = EntityUtils.toString(responseEntity);
	        return jsonString;
	      } 
	      logger.error("接口state：{},url:{}", state, url);
	    } catch (Exception e) {
	    	logger.error("url:{}", url, e.getMessage());
	    } finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException iOException) {
				}
			}
	      try {
	        httpclient.close();
	      } catch (IOException iOException) {}
	    } 
	    return null;
	  }
}
